package org.lab.io.reader;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.LinkedList;

import org.apache.log4j.Logger;
import org.lab.data.Quote;
import org.lab.data.QuoteComparator;
import org.lab.io.IDownloader;


public class DataCSVReader implements IDownloader{
	
	private static Logger logger = Logger
	.getLogger(DataCSVReader.class);
	
	private LinkedList<Quote> quotes;

	private String fileName;
	//private String extension;

	private DateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
	protected String currentLine = null;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public DataCSVReader(String fileName) {
		super();
		this.fileName = fileName;
		//this.extension = fileName.substring(fileName.lastIndexOf("."), fileName.length());
	}
	
	public LinkedList<Quote> importData() throws IOException {
		quotes = new LinkedList<Quote>();
		
		BufferedReader in;
		in = new BufferedReader(new FileReader(fileName));
		
		while ((currentLine = in.readLine()) != null) {
			String[] values = currentLine.split(",");

			Quote quote = new Quote();
			if (values.length == 7) {
				try {
					quote.setDate(DATE_FORMATTER.parse(values[0]));
					quote.setOpen(Float.valueOf(values[1]));
					quote.setClose(Float.valueOf(values[2]));
					quote.setHigh(Float.valueOf(values[3]));
					quote.setLow(Float.valueOf(values[4]));
					quote.setVolume(Long.valueOf(values[5]));
					if (!quotes.contains(quote.getDate())) {
						quotes.add(quote);
					}
				} catch (NumberFormatException ex) {
					logger.error("Error en el formato leido " + currentLine
							+ " en posicion numero " + (quotes.size() + 1));
				} catch (ParseException ex) {
					logger.error("Error en el formato leido " + currentLine
							+ " en posicion numero " + (quotes.size() + 1));					
				}
			} else {
				logger.error("Error en el formato leido " + currentLine
						+ " en posicion numero " + (quotes.size() + 1));
			}
		}
		Collections.sort(quotes, new QuoteComparator());
		Collections.reverse(quotes);
		
		return quotes;
	}
	
}